//
//  WBStatusListViewModel.swift
//  传智微博
//
//  Created by zhoujiming on 2017/1/22.
//  Copyright © 2017年 gmcc. All rights reserved.
//

import Foundation
import SDWebImage

private let maxPullupTryTimes = 3


class WBStatusListViewModel{
    
    lazy var statusList = [WBStatusViewModel]()
    
    private var pullupErrorTimes = 0
    
    
    func loadStatus(pullup: Bool, completion : @escaping (_ isSuccess:Bool,_ shouldRefresh : Bool)->()){
        
        if pullup && pullupErrorTimes > maxPullupTryTimes{
            completion(true, false)
            
            return
        }
        
        let since_id = pullup ? 0 : (statusList.first?.status.id ?? 0)
        
        let max_id = !pullup ? 0 : (statusList.last?.status.id ?? 0)
        
        WBNetworkManager.shared().statusList(since_id: since_id, max_id: max_id) { (list, isSuccess) in
            
            if !isSuccess {
                completion(false, false)
                return
            }
            
            //  字典转模型
            // 定义结果可变数组
            var array = [WBStatusViewModel]()
            
            for dict in list ?? []{
                
                // 创建微博模型
                guard let model = WBStatus.yy_model(with: dict) else {
                    continue
                }
                
                // 将model添加到数组
                array.append(WBStatusViewModel(model: model))
                
            }
//            guard let array = NSArray.yy_modelArray(with: WBStatus.self, json: list ?? []) as? [WBStatus] else {
//                completion(isSuccess, false)
//                return
//            }
            
            print("刷新到\(array.count)条记录")
            
            
            if pullup {
                self.statusList += array
            }
            else
            {
                self.statusList = array + self.statusList
            }
            
            if pullup && array.count == 0 {
                self.pullupErrorTimes  += 1
                
                completion(isSuccess, false)
            }
            else
            {
                self.cacheSingleImage(list: array, finished: completion)
                // completion(isSuccess, true)
            }
        }
    }
    
    /// 缓存本次下载微博数据中的单张图像
    /// 缓存完单张图像，并且修改过配图之后，再回调，才能保证表格等比例显示单张图像
    /// - Parameter list: <#list description#>
    private func cacheSingleImage(list: [WBStatusViewModel], finished : @escaping (_ isSuccess:Bool,_ shouldRefresh : Bool)->()){
        
        // 调度组
        let group = DispatchGroup()
        
        // 记录数据长度
        var length = 0
        
        
        for vm in list {
            if vm.picURLs?.count != 1{
                continue
            }
            
            // 获取图像模型
            guard let pic = vm.picURLs![0].thumbnail_pic,
                let url = URL(string: pic) else{
                    continue
            }
            
            // A.入组
            group.enter()
            
            // 下载图像
            // 图像下载完成之后会自动保存在沙盒中，文件路径是url的md5
            // 如果已经存在，则会加载已经缓存的图像，回调依然会调用
            SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, _, _, _, _) in
                
                if let image = image,
                    let data = UIImagePNGRepresentation(image){
                    length += data.count
                    
                    // 缓存成功，更新视图大小
                    vm.updateSingleImageSize(image: image)
                }
                // B.出组
                group.leave()
            })
        }
        
        // 监听调度组
        group.notify(queue: DispatchQueue.main){
            print("图像缓存完成\(length / 1024)K")
            
            // 执行回调
            finished(true, true)
        }
    }
}
